//
//  MKNetWorkTool.swift
//  MOKOAnnounce
//
//  Created by 曹相召 on 2017/7/12.
//  Copyright © 2017年 cc.moko. All rights reserved.
//

import UIKit
import Alamofire

class MKNetWorkTool: NSObject {
    //GET请求
    class func getRequest(url:String, params:[String:Any]?,success : @escaping (_ response:HTTPURLResponse,_ responseObject:String)->(),failture : @escaping (_ response:HTTPURLResponse?,_ error:Error)->()){

        print("params --- \(String(describing: params))")
        let api = UserDefaults.standard.object(forKey: apiurlStr as String) as! String
        let apiurl = api.appending("/")
        let requestUrl = apiurl.appending(url)
        print(requestUrl)


        let quest = NSMutableURLRequest.init(url: URL.init(string: requestUrl)!)
        let httpHeader = self.headerappend(path: (quest.url?.absoluteString)!)

        Alamofire.request(requestUrl, method: HTTPMethod.get, parameters: nil, encoding: JSONEncoding.default, headers: httpHeader).responseJSON { (response) in
            //        response.response?.statusCode
            switch response.result {
            case .success:
                print("response.result.value! ---- \(response.result.value!)")
                if let json = response.data{
                    if(json.count > 0){
                        let str = String(data:json, encoding: String.Encoding.utf8)!
                        print(str)
//                        let object = try!JSONSerialization.jsonObject(with: json, options: .mutableContainers)
                        success(response.response!, str)
                    }else{
                        success(response.response!, "")
                    }
                }
            case .failure:
                failture(response.response,response.error!)
                break
            }
        }
    }
    //POST请求
    class func postRequest(url:String, params:[String:Any]?,success : @escaping (_ response:HTTPURLResponse,_ responseObject:String)->(),failture : @escaping (_ response:HTTPURLResponse?,_ error:Error)->()){
        print("params --- \(String(describing: params))")
        let api = UserDefaults.standard.object(forKey: apiurlStr as String) as! String
        let apiurl = api.appending("/")
        let requestUrl = apiurl.appending(url)
        print(requestUrl)

        let quest = NSMutableURLRequest.init(url: URL.init(string: requestUrl)!)
        let httpHeader = self.headerappend(path: (quest.url?.absoluteString)!)

        //设置超时
        Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 10
        
        Alamofire.request(requestUrl, method: HTTPMethod.post, parameters: params, encoding: JSONEncoding.prettyPrinted, headers: httpHeader).responseJSON { (response) in
    //        response.response?.statusCode
            switch response.result {
            case .success:
                print("response.result.value! ---- \(response.result.value!)")
                if let json = response.data{
                    if(json.count > 0){
                        let str = String(data:json, encoding: String.Encoding.utf8)!
                        print(str)
//                        let object = try!JSONSerialization.jsonObject(with: json, options: .mutableContainers)
                        success(response.response!, str)
                    }else{
                        success(response.response!, "")
                    }
                }
            case .failure:
                failture(response.response,response.error!)
                break
            }
        }
    }
    //httpHeader生成
    class func headerappend(path:String) -> HTTPHeaders {
        let mutableURLRequest:NSMutableURLRequest = NSMutableURLRequest.init(url: NSURL.init(string:path as String)! as URL)
        let relativePath = mutableURLRequest.url!.relativePath
        let userid = UserDefaults.standard.object(forKey: useridStr as String)
        let dict:NSDictionary = ["uri":relativePath,"udid":OpenUDID.value(),"user":userid ?? ""]
        let encryptedData = try! RNEncryptor.encryptData(dict.mj_JSONData(), with: kRNCryptorAES256Settings, password: MOKO_APP_SECRET)
        let safe_hmac = encryptedData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        let headerValue = MOKO_APP_KEY.appending(":").appending(safe_hmac)
        return ["X-MOKO-AUTH":headerValue as String,"Content-Type":"application/json"]
    }
}



